package cn.zhqr.core.service;

import cn.zhqr.command.CommandKit;
import cn.zhqr.common.bean.response.ErrorCode;
import cn.zhqr.common.bean.response.OutResponse;
import cn.zhqr.common.config.RiskConfig;
import cn.zhqr.core.utils.WashCardKit;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 洗车订单风险控制服务
 */
public class UserOrderRiskControlService {
    public static final UserOrderRiskControlService instance = new UserOrderRiskControlService();
    public static final Logger logger = Logger.getLogger(UserOrderRiskControlService.class);

    public OutResponse checkoutUserOrder(UserOrder userOrder){
        if(userOrder == null){
            return OutResponse.buildError(ErrorCode.INVALID_PARAM,"订单不能为空");
        }

        BigDecimal totalFee = userOrder.getOrderAmount();
        BigInteger orderNo = userOrder.getOrderNo();
        Long deviceId = userOrder.getDeviceId();

        StationSetting stationSetting = StationSetting.dao.findByStationId(userOrder.getStationId());

        UserWashCard userWashCard = UserWashCard.dao.findById(userOrder.getGoodsId());


        Station station = Station.dao.findById(userOrder.getStationId());
        User user = User.dao.findByUserId(userOrder.getUserId());

        //检查卡是否可用
        OutResponse checkResult = UserCardService.instance.checkUserWashCard(userWashCard,user,station);
        if(!checkResult.isSuccess()){
            logger.info("洗车卡可用性校验不通过 order_no:"+orderNo+ " device_id:"+deviceId+ " card_id:"+userWashCard.getId()+" userid:"+user.getId()+" result:"+ JSON.toJSONString(checkResult));
            int endReason = UserOrder.END_REASON_RISK_CARD_UNAVAILABLE;
            if(checkResult.getCode() == ErrorCode.WASH_CARD_TODAY_USED_UP.code){
                endReason = UserOrder.END_REASON_RISK_TOO_MANY_TIMES;
            }
            UserOrderService.instance.endOrder(userOrder.getOrderNo(),endReason);
            CommandKit.end(deviceId,orderNo);
            return checkResult;
        }

        //代金卡检查余额
        if(userWashCard.getCardType()==WashCard.TYPE_VALUE){
            logger.info("检查卡内余额 order_no:"+orderNo+ " device_id:"+deviceId+ " 消费合计："+totalFee+"元"+" 卡内余额："+userWashCard.getBalance());
            if(totalFee.compareTo(userWashCard.getBalance()) >=0 ){
                logger.info("消费金额已超出卡内余额，强制结算 order_no:"+orderNo+ " device_id:"+deviceId+ " 消费合计："+totalFee+"元"+" 卡内余额："+userWashCard.getBalance());
                UserOrderService.instance.endOrder(userOrder.getOrderNo(),UserOrder.END_REASON_OVERSPEND);
                CommandKit.end(deviceId,orderNo);
                return OutResponse.buildError(ErrorCode.BALANCE_NOT_ENOUGH);
            }
        }


        //检查单次最大消费金额
        if(totalFee.compareTo(BigDecimal.ZERO)>0) {
            BigDecimal maxAmount = WashCardKit.getMaxOrderAmount(userWashCard, stationSetting);//本次最大消费金额
            if (totalFee.compareTo(maxAmount) >= 0) {
                logger.info("消费金额超过单次上限，强制结算 order_no:" + orderNo + " device_id:" + deviceId + " 消费合计：" + totalFee + "元" + " 最大消费金额：" + maxAmount);
                UserOrderService.instance.endOrder(userOrder.getOrderNo(), UserOrder.END_REASON_OVER_MAX_AMOUNT);
                CommandKit.end(deviceId, orderNo);
                return OutResponse.buildError(ErrorCode.ORDER_OVER_AMOUNT);
            }
        }


        //检查单次最大时长
        if(userOrder.getUpdateTime()!=null && userOrder.getStarTime()!=null){
            Long maxTime = WashCardKit.getMaxOrderTime(userWashCard,stationSetting);//本次最大洗车时长
            long duration = userOrder.getUpdateTime().getTime() - userOrder.getStarTime().getTime();
            if(duration >= maxTime*60*1000) {
                logger.info("使用时长超过单次上限，强制结算 order_no:" + orderNo + " device_id:" + deviceId + " 消费合计：" + totalFee + "元" + " 时长：" +duration+" 最大时长："+maxTime);
                UserOrderService.instance.endOrder(userOrder.getOrderNo(),UserOrder.END_REASON_OVERTIME);
                CommandKit.end(deviceId, orderNo);
                return OutResponse.buildError(ErrorCode.ORDER_OVER_TIME);
            }
        }

        return OutResponse.buildSuccess("校验通过",null);
    }
}
